# -*- coding: utf-8 -*-
import logging
import os
import smtplib
import sys

from email.mime.text import MIMEText
from email.utils import formataddr

from jinja2 import Template

from config import load_config
from fetch_top_4_conf_countdown import update_ical_url, fetch_top4_conf_countdown
from parse_args import parse_args


def send_email(smtp_conf, to_addr, subject, html_body, email_from_name = "论文追踪"):
    msg = MIMEText(html_body, 'html')
    msg['Subject'] = subject
    msg['From'] = formataddr((email_from_name, smtp_conf['email_from']))
    # msg['From'] = f"{email_from_name} <{smtp_conf['email_from']}>"
    msg['To'] = to_addr
    logging.info(f"Sending email to {to_addr}")
    try:
        with smtplib.SMTP(smtp_conf['server'], smtp_conf['port']) as server:
            if smtp_conf.get('smtp_enable_starttls_auto', False):
                server.starttls()
            server.login(smtp_conf['user_name'], smtp_conf['password'])
            server.send_message(msg)
        logging.info(f"邮件已发送至 {to_addr}")
    except Exception as e:
        logging.error(f"发送邮件失败至 {to_addr}: {e}")


if __name__ == '__main__':
    # config_path = sys.argv[1] if len(sys.argv) > 1 else 'config.yml'
    # config = load_config(config_path)
    args = parse_args()

    run_mode = args.mode

    # 加载配置文件
    config_path = args.config
    config = load_config(config_path)
    mail_conf = config['email']
    smtp_conf = config['smtp']

    template = mail_conf['template']

    save_path_ical = "data/deadlines-all.ical"
    if not os.path.exists(save_path_ical):
        update_ical_url(save_file="data")
    conf_list = fetch_top4_conf_countdown(save_path_ical)
    print(conf_list)


    tpl = Template(template)
    new_papers = {'TITS': [{'title': 'A Systematic Survey of Digital Twin Applications: Transferring Knowledge From Automotive and Aviation to Maritime Industry', 'link': 'http://ieeexplore.ieee.org/document/10902076', 'summary': 'Digital twin (DT) technology, which creates virtual representations of physical systems to optimize their life-cycle, has drawn significant attention across various industries. The automotive and aviation industries have been pioneers in adopting DTs for enhanced efficiency, predictive maintenance, and real-time decision-making. However, the maritime industry, crucial to global trade and logistics, has lagged in DT implementation. This paper aims to bridge this gap by systematically surveying DT applications in the automotive and aviation industries and exploring how this knowledge can be transferred to the maritime industry. By analyzing existing literature, identifying key trends, and summarizing best practices, a comprehensive roadmap is provided for maritime industry adoption of DT technology. The surveyed papers are selected systematically following the PRISMA statement and categorized based on characteristics such as single vs. multiple systems, modeling methods (model-driven, data-driven, and hybrid), and life-cycle phases. We introduce DT models using a five-dimensional framework and analyze their characteristics in terms of research object, subsystem application, and modeling method. Additionally, DT applications from a product life-cycle perspective, covering design, manufacturing, operation, and maintenance phases are examined. Knowledge transfer from the automotive and aviation industries to the maritime industry is summarized. In the automotive industry, DTs enhance vehicle efficiency and safety, particularly for autonomous and electric vehicles. Aviation DT research focuses on predictive maintenance, pilot training, and real-time monitoring to improve operational efficiency and safety. The maritime industry faces data challenges and operational complexity but has significant potential for DTs to enhance ship performance, safety, and predictive maintenance.', 'published': 'MON, 24 FEB 2025 09:17:26 -0400', 'authors': 'Runze Mao;Yuanjiang Li;Guoyuan Li;Hans Petter Hildre;Houxiang Zhang;', 'paper_summary_chinese': '数字孪生（DT）技术通过创建物理系统的虚拟表示来优化其生命周期，已在各个行业引起广泛关注。汽车和航空业一直是采用DT的先驱，以提高效率、进行预测性维护和做出实时决策。然而，对全球贸易和物流至关重要的海事行业在DT实施方面却有所滞后。本文旨在通过系统地调研汽车和航空业的DT应用，并探索如何将这些知识转移到海事行业，从而弥合这一差距。通过分析现有文献、识别关键趋势并总结最佳实践，为海事行业采用DT技术提供了一份全面的路线图。调研的论文遵循PRISMA声明进行系统选择，并根据单一系统与多系统、建模方法（模型驱动、数据驱动和混合）以及生命周期阶段等特征进行分类。我们使用五维框架介绍DT模型，并从研究对象、子系统应用和建模方法等方面分析其特征。此外，还从产品生命周期的角度，涵盖设计、制造、运营和维护阶段，对DT应用进行了考察。总结了从汽车和航空业到海事行业的知识转移。在汽车行业，DT增强了车辆效率和安全性，特别是对于自动驾驶和电动汽车。航空DT研究侧重于预测性维护、飞行员培训和实时监控，以提高运营效率和安全性。海事行业面临数据挑战和运营复杂性，但在提高船舶性能、安全性和预测性维护方面具有巨大的DT潜力。\n'}]}
    html = tpl.render(truename="大哥", feeds=new_papers, confs=conf_list)
    send_email(smtp_conf, "zyguo2020@163.com", "测试", html)
